package com.ankiang.mykeys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Toast;

import com.ankiang.mykeys.common.Constant;
import com.ankiang.utils.DBManager;
import com.ankiang.utils.HttpUtil;
import com.etsy.android.grid.StaggeredGridView;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

public class ShortcutActivity extends AppCompatActivity implements
        AbsListView.OnScrollListener, AbsListView.OnItemClickListener {


    // 本地缓存数据，SQLLite
    DBManager dbManager;

    public final String TAG = "ShortcutActivity";

    // 瀑布流
    private StaggeredGridView mGridView;

    // 是否还有数据
    private boolean mHasRequestedMore;

    // 软件适配器
    private ShortcutAdapter mAdapter;

    // 收到的数据
    private JSONArray mData;

    // 是否需要更新
    private boolean needUpdate = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shortcut_activity);

        init(savedInstanceState);
        initView(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    void init(final Bundle savedInstanceState) {
        Log.i(TAG, "http asyn...");

        final Intent intent = this.getIntent();

        dbManager = new DBManager(this.getApplicationContext());
        mGridView = (StaggeredGridView) findViewById(R.id.shortcut_grid_view);

        String appId = intent.getStringExtra("appId");
        if (Utils.isEmpty(appId)) {
            Log.e(TAG, "从intent中取appId失败！！！");
            appId = "2";
        }else {
            Log.i(TAG, "取到了appId="+appId);
        }

        String urlFormat = "http://mykeys.sinaapp.com/ifc/getItemList.php?appid=%s";
        String urlString = String.format(urlFormat, appId);
        String key = Constant.K_APP_PREFIX + appId;
        String json = dbManager.get(key);
        dbManager.update(Constant.K_CURRENT_DATA, key);
        if (needUpdate || "".equals(json)) {
            Log.i(TAG, "using http");
            HttpUtil.get(urlString, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) { // 获取数据成功会调用这里
                    if (response != null) {
                        String s = response.toString();

                        String appId = intent.getStringExtra("appId");
                        if (Utils.isEmpty(appId)) {
                            Log.e(TAG, "没有取到appId！！！");
                            appId = "2";
                        }else {
                            Log.i(TAG, "取到的appId="+appId);
                        }
                        dbManager.update(Constant.K_APP_PREFIX + appId, s);
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    if (response != null) {
                        Log.i(TAG, "http asyn onSuccess JSONObject...");
                        try {
                            JSONObject res = (JSONObject) response.get("res");
                            int code = res.getInt("code");
                            if (code != 0) {
                                String msg = res.getString("msg");
                                Log.i(TAG, "Error: " + msg);
                                //Toast.makeText(this, "Error: " + msg, Toast.LENGTH_LONG).show();
                                return;
                            }
                            mData = response.getJSONArray("data");
                            if (mData !=null) {
                                Log.i(TAG, response.toString());
                                initView(savedInstanceState);
                                Log.i(TAG, "成功取到了数据");
                            }else {
                                Log.e(TAG, "Error: 取数据失败");
                            }



                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.toString());
                            //TODO
                            Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();

                        }
                        String s = response.toString();


                        String appId = intent.getStringExtra("appId");
                        if (Utils.isEmpty(appId)) {
                            appId = "2";
                        }
                        String key = Constant.K_APP_PREFIX + appId;
                        dbManager.update(key, s);

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { // 失败，调用
                    if (throwable != null) {
                        //textView.setText(throwable.getMessage());
                    }
                }

                public void onFinish() { // 完成后调用，失败，成功，都要掉
                    super.onFinish();
                    Log.i(TAG, "http asyn onFinish");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    if (throwable != null) {
                        //textView.setText(throwable.getMessage());
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    if (throwable != null) {
                        //textView.setText(throwable.getMessage());
                    }
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    //textView.setText(responseString);
                }

            });
        } else {
            Log.i(TAG, "using cached data");
            try {
                JSONObject response = new JSONObject(json);
                JSONObject res = (JSONObject) response.get("res");
                int code = res.getInt("code");
                if (code != 0) {
                    String msg = res.getString("msg");
                    Toast.makeText(this, "Error: " + msg, Toast.LENGTH_LONG).show();
                    return;
                }
                mData = response.getJSONArray("data");


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();

            }
        }

    }


    public void initView(final Bundle savedInstanceState) {

        mGridView = (StaggeredGridView) findViewById(R.id.shortcut_grid_view);

        if (savedInstanceState == null) {
//            final LayoutInflater layoutInflater = getLayoutInflater();

//            View header = layoutInflater.inflate(R.layout.home_list_item_header_footer, null);
//            View footer = layoutInflater.inflate(R.layout.home_list_item_header_footer, null);
//            TextView txtHeaderTitle = (TextView) header.findViewById(R.id.txt_title);
//            TextView txtFooterTitle = (TextView) footer.findViewById(R.id.txt_title);
//            txtHeaderTitle.setText("THE HEADER!");
//            txtFooterTitle.setText("THE FOOTER!");
//
//            mGridView.addHeaderView(header);
//            mGridView.addFooterView(footer);
        }

        if (mAdapter == null) {
            mAdapter = new ShortcutAdapter(this, R.id.app_des);
        }

        if (mData == null) {
            mData = new JSONArray();
        }

        int current = 0;
        int APP_SHOW_COUNT = 500;
        for (int i = 0; i + current < mData.length() && i < APP_SHOW_COUNT; i++) {
            JSONObject data;
            try {
                data = mData.getJSONObject(i + current);
                mAdapter.add(data);
                current++;
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG);
                break;
            }
        }


        mGridView.setAdapter(mAdapter);
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
    }

    @Override
    public void onScrollStateChanged(final AbsListView view, final int scrollState) {
        Log.d(TAG, "onScrollStateChanged:" + scrollState);
    }

    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
        Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
                " visibleItemCount:" + visibleItemCount +
                " totalItemCount:" + totalItemCount);
        // our handling
        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                Log.d(TAG, "onScroll lastInScreen - so load more");
                mHasRequestedMore = true;
                onLoadMoreItems();
            }
        }
    }

    private void onLoadMoreItems() {

        int current = 0;
        int APP_SHOW_COUNT = 500;
        for (int i = 0; i + current < mData.length() && i < APP_SHOW_COUNT; i++) {
            JSONObject data;
            try {
                data = mData.getJSONObject(i + current);
                mAdapter.add(data);
                current++;
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG);
                break;
            }
        }
        // notify the adapter that we can update now
        mAdapter.notifyDataSetChanged();
        mHasRequestedMore = false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//        ShortcutAdapter.ViewHolder vh = (ShortcutAdapter.ViewHolder) view.getTag();
//        String s = vh.txtAppDes.getText().toString();
//        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}
